﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NlpTrainApp.Bll.Uie;
using System.Threading;
using System.Threading.Tasks;

namespace NlpTrainApp.Webapi
{
    /// <summary>
    /// 控制台生命周期
    /// </summary>
    internal class LifetimeEventsHostedService : IHostedService
    {
        private readonly ILogger logger;
        private readonly IHostApplicationLifetime appLifetime;
        private readonly ExtractServiceBll extractService;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="logger">logger</param>
        /// <param name="appLifetime">app</param>
        public LifetimeEventsHostedService(
            ILogger<LifetimeEventsHostedService> logger,
            IHostApplicationLifetime appLifetime, ExtractServiceBll extractServiceBll)
        {
            this.logger = logger;
            this.appLifetime = appLifetime;
            this.extractService = extractServiceBll;
        }
        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="cancellationToken">停止</param>
        /// <returns></returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            appLifetime.ApplicationStarted.Register(OnStarted);
            appLifetime.ApplicationStopping.Register(OnStopping);
            appLifetime.ApplicationStopped.Register(OnStopped);
            return Task.CompletedTask;
        }
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="cancellationToken">停止</param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
        /// <summary>
        /// 已经开始
        /// </summary>
        private void OnStarted()
        {
            logger.LogTrace("OnStarted has been called.");
            _ = extractService.RunClassify();
            // Perform post-startup activities here
        }
        /// <summary>
        /// 正在停止
        /// </summary>
        private void OnStopping()
        {
            logger.LogTrace("OnStopping has been called.");
            // Perform on-stopping activities here
        }
        /// <summary>
        /// 已经停止
        /// </summary>
        private void OnStopped()
        {
            logger.LogTrace("OnStopped has been called.");
            // Perform post-stopped activities here
        }
    }
}
